// 这个插件文件，统一注册全局组件，统一注册全局指令
import XtxSkeleton from "../components/skeleton/index.vue";
import XtxCarousel from "../components/carousel/index.vue";
import XtxMore from "./more/index.vue";
import XtxCity from "./city/index.vue";
import type { App } from "vue";
import defaultImg from "@/assets/images/200.png";
import { useIntersectionObserver } from "@vueuse/core";
import XtxBread from "./bread/index.vue";
import XtxBreadItem from "./bread/item.vue";

export default {
  // app 创建出来的应用实例  类型是固定的 => vue库内部会提供好实例类型的
  install(app: App) {
    // 为了和组件库统一  组件库都是这么处理的，我们这么封装，和组件库同步了
    app.component("XtxSkeleton", XtxSkeleton);
    app.component("XtxCarousel", XtxCarousel);
    app.component("XtxMore", XtxMore);
    app.component("XtxBread", XtxBread);
    app.component("XtxBreadItem", XtxBreadItem);
    app.component("XtxCity", XtxCity);

    // 构建指令
    // <img :src="item.picUrl" ref="target"/>
    // <img v-lazy="item.picUrl" ref="target"/>

    app.directive("lazy", {
      // 指令所在的元素节点 被插入  父节点时触发
      // inserted vue2中
      mounted(el, binding) {
        // el 目标元素，binding 指令相关的信息
        const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
          if (isIntersecting) {
            // 停止监听
            stop();
            // 给el元素设置src属性
            el.src = binding.value;
          }
        });
        el.src = binding.value;

        // 如果图片加载失败，显示一张默认的图片
        el.onerror = () => {
          // 设置加载失败的图片
          el.src = defaultImg;
        };
      },
    });
  },
};
